/* eslint-disable @typescript-eslint/no-explicit-any */
import { PanelItemController } from '@ibiz-template/runtime';
import { IPanelField } from '@ibiz/model-core';
import { clone } from 'ramda';

export class DynamicTextExtendController extends PanelItemController<IPanelField> {
  /**
   * 实体属性名称
   *
   * @protected
   * @type {string}
   * @memberof DynamicTextExtendController
   */
  protected viewFieldName: string = '';

  /**
   * 主键属性
   *
   * @protected
   * @type {string}
   * @memberof DynamicTextExtendController
   */
  protected keyAppDEFieldId: string = '';

  /**
   * 实体方法
   *
   * @protected
   * @type {string}
   * @memberof DynamicTextExtendController
   */
  protected deMethod: string = 'save';

  /**
   * 初始化
   *
   * @protected
   * @return {*}  {Promise<void>}
   * @memberof DynamicTextExtendController
   */
  protected async onInit(): Promise<void> {
    await super.onInit();
    this.viewFieldName = this.model.viewFieldName?.toLowerCase() || '';
    const appDataEntity = await ibiz.hub.getAppDataEntity(
      this.panel.model.appDataEntityId!,
      this.panel.model.appId,
    );
    const userTag = (this.model as any).userTag;
    if (userTag) {
      const params = JSON.parse(userTag);
      this.deMethod = params.deMethod || 'save';
    }
    this.keyAppDEFieldId = appDataEntity.keyAppDEFieldId || '';
  }

  /**
   * 获取数据值
   *
   * @return {*}
   * @memberof DynamicTextExtendController
   */
  public getDataValue() {
    const { viewFieldName } = this.model;
    if (viewFieldName) {
      return this.data[viewFieldName.toLowerCase()];
    }
  }

  /**
   * 保存数据
   *
   * @memberof DynamicTextExtendController
   */
  public async saveData() {
    const tempContext = clone(this.panel.context);
    const tempParams = clone(this.panel.params);
    const app = ibiz.hub.getApp(tempContext.srfappid);
    const view = this.panel.view;
    const value = this.getDataValue();
    const data = {
      [this.keyAppDEFieldId]: this.data[this.keyAppDEFieldId],
      [this.viewFieldName]: value,
    };
    view.startLoading();
    const res = await app.deService.exec(
      this.panel.model.appDataEntityId!,
      this.deMethod,
      tempContext,
      data,
      tempParams,
    );
    view.endLoading();
    return res;
  }

  /**
   * 设置面板数据的值
   *
   * @param {unknown} value
   * @param {string} [name]
   * @return {*}  {Promise<void>}
   * @memberof DynamicTextExtendController
   */
  async setDataValue(value: unknown, name?: string): Promise<void> {
    const { viewFieldName } = this.model;
    const _name = name || viewFieldName?.toLowerCase();
    if (this.dataParent.setDataValue) {
      await this.dataParent.setDataValue(_name!, value);
    }
  }
}
